package com.quan.api.wx.pay;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayNativeOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.quan.api.wx.vo.ScanPayVo;
import com.quan.commons.core.biz.support.MyBaseController;
import com.quan.commons.core.configuration.WxPayConfiguration;
import com.quan.commons.core.properties.SystemValueProperties;
import com.quan.commons.core.utils.*;
import com.quan.mall.entity.FmsFinanceCashFlow;
import com.quan.mall.entity.OmsOrder;
import com.quan.mall.service.FmsFinanceCashFlowService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 扫码付款
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/api/wx/scan")
public class WxScanPayController extends MyBaseController {

	//@Autowired
	//private WxPayService wxPayService;

	@Autowired
	private SystemValueProperties systemValueProperties;

	@Autowired
	private FmsFinanceCashFlowService fmsFinanceCashFlowService;

	/**
	 * 扫码支付生成二维码
	 * @return
	 * @throws WxPayException
	 */
	@PostMapping(value = "pay")
	public Object pay(@RequestBody ScanPayVo vo) throws WxPayException {
		log.info("========================>微信扫码支付<========================");
		log.info("==>发起时间：{}", LocalDateTime.now());

		final WxPayService wxPayService = WxPayConfiguration.getPayService(vo.getAppId());

		//1生成订单号
		String orderSn = OrderUtils.getSN();

		// 通过统一下单获取二维码链接
		WxPayUnifiedOrderRequest unifiedOrderRequest = new WxPayUnifiedOrderRequest();	
		unifiedOrderRequest.setOutTradeNo(orderSn);
		unifiedOrderRequest.setProductId(orderSn);
		unifiedOrderRequest.setBody(vo.getBody());
		unifiedOrderRequest.setTotalFee(vo.getAmount().intValue());
		unifiedOrderRequest.setSpbillCreateIp(IpHelper.getIpAddr(request));
		unifiedOrderRequest.setNotifyUrl(this.systemValueProperties.getWechat().getScanpayNotifyUrl());
		unifiedOrderRequest.setTradeType(WxPayConstants.TradeType.NATIVE);
		
		// 创建微信预支付订单
		WxPayNativeOrderResult createOrder = wxPayService.createOrder(unifiedOrderRequest);

		// 二维码链接，生产二维码图片字节数组，返回前端，直接显示。
		byte[] createScanPayQrcodeMode2 = wxPayService.createScanPayQrcodeMode2(createOrder.getCodeUrl(), null, null);

		log.info("==>支付二维码生成：{}", "成功");

		return CommonUtils.converterImageBase64(createScanPayQrcodeMode2);
	}

	/**
	 * 扫码支付回调
	 * @param xmlData
	 * @return
	 * @throws WxPayException
	 */
	@PostMapping("notify")
	public String parseScanPayNotifyResult(@RequestBody String xmlData) throws WxPayException {
		log.info("==>微信扫码支付回调通知处理");

		try {
			final WxPayService wxPayService = WxPayConfiguration.getPayService("wx4d9c77825c409a14");
			final WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlData);

			log.info("==>支付用户OPENID：{}", result.getOpenid());
			log.info("==>支付金额：{}元", AmountUtils.changeF2Y(result.getTotalFee().longValue()));
			log.info("==>订单编号：{}", result.getOutTradeNo());
			log.info("==>微信支付订单号：{}", result.getTransactionId());
			log.info("==>支付完成时间：{}", DateUtil.parse(result.getTimeEnd()));
			log.info("==>微信支付回调结果：{}, {}", result.getReturnCode(), result.getResultCode());

			//微信支付通信标识：成功
			if (result.getReturnCode().equals("SUCCESS")) {
				// 交易状态：成功
				if (result.getResultCode().equals("SUCCESS")) {
					log.info("==>交易状态：成功");
					////////////////////////////////////////////////////////////
					// 业务处理开始
					////////////////////////////////////////////////////////////

					//this.saveFinanceInfo()

					log.info(">>>>>>>>>>>>>>>>>>>微信订单支付回调处理结束<<<<<<<<<<<<<<<<<<<");
					return WxPayNotifyResponse.success("成功");

				} else {
					log.error("==>交易状态：失败");
				}
			} else {
				log.error("微信支付通信标识：失败，错误信息：{}", result.getReturnMsg());
			}
		} catch (Exception e) {
			log.error("==>微信订单支付回调处理发生异常：错误信息：{}", e.getMessage());
		}

		return WxPayNotifyResponse.fail("失败");
	}

	private void saveFmsFlowFundInfo(WxPayOrderNotifyResult result, OmsOrder order) {
		FmsFinanceCashFlow cashFlow = new FmsFinanceCashFlow();
		cashFlow.setOpenId(result.getOpenid());
		cashFlow.setAppId(result.getAppid());
		cashFlow.setMchId(result.getMchId());
		cashFlow.setMemberId(order.getMemberId());
		cashFlow.setMemberName(order.getMemberUsername());
		cashFlow.setTransactionId(result.getTransactionId());
		// 会员充值
		cashFlow.setTransactionType(4);
		cashFlow.setAmount(order.getPayAmount());
		cashFlow.setRemarks(order.getPaymentBody());

		Map<String, Object> extraMap = new HashMap<String, Object>();
		cashFlow.setExtraJson(JSON.toJSONString(extraMap));

		this.fmsFinanceCashFlowService.save(cashFlow);
	}

}
